<?php

/**
 * 访客域名来源信息分析报表
 * File Name：GuestRefererModel.php
 * File Encoding：UTF-8
 * File New Time：2014-8-28 11:20:28
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GuestRefererModel extends BaseModel {

    public function tableName() {
        return '{{guest_referer}}';
    }

    public function rules() {
        return array(
            array('root_domain,domain,frequency,years,month,day,created_time,update_time', 'safe'),
        );
    }

    //数据保存前置操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->created_time = $this->update_time = time();
        } else {
            $this->update_time = time();
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 获取一级域名，例如：www.1zw.com 取得 1zw.com部分
     * @param type $url
     * @return array array('root_domain','domain')
     */
    public function getDomain($url) {
        $host = strtolower($url);
        if (strpos($host, '/') !== false) {
            $parse = @parse_url($host);
            $host = $parse ['host'];
        }
        $topleveldomaindb = array('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me', 'com.cn');
        $str = '';
        foreach ($topleveldomaindb as $v) {
            $str .= ($str ? '|' : '') . $v;
        }
        $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
        if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
            $domain = $matchs ['0'];
        } else {
            $domain = $host;
        }
        return array('root_domain' => $domain, 'domain' => $host);
    }

    //把基本数据记录到redis里
    public function redisFenxi($data) {
        if (empty($data['referer']) || empty($data)) {
            return false;
        }
        $domain = $this->getDomain($data['referer']);
        if ($domain['root_domain'] == '1zw.com') {
            return false;
        } else {
            $data['root_domain'] = $domain['root_domain'];
            $data['domain'] = $domain['domain'];
        }
        if (isset($data['access_time'])) {
            $access_time = $data['access_time'];
        } else {
            $access_time = time();
        }
        $data['years'] = (int) date('Y', $access_time);
        $data['month'] = (int) date('m', $access_time);
        $data['day'] = (int) date('d', $access_time);
        if (defined('YII_DEBUG') && YII_DEBUG == false) {
            try {
                $key = "guest_referer_frequency_{$domain['domain']}";
                RedisCluster::getInstance()->incr($key);
                RedisCluster::getInstance()->set('guest_referer_data_' . $domain['domain'], json_encode($data));
                RedisCluster::getInstance()->getRedis()->sadd('guest_referer_list', $domain['domain']);
            } catch (Exception $exc) {
                
            }
        }
    }

    //执行分析
    public function sendFenxi() {
        //返回一个集合的全部值
        $lisKey = RedisCluster::getInstance()->getRedis()->sdiff('guest_referer_list');
        if (empty($lisKey)) {
            $lisKey = array();
        }
        RedisCluster::getInstance()->remove('guest_referer_list');
        foreach ($lisKey as $domain) {
            $key = "guest_referer_frequency_{$domain}";
            //获取次数
            $frequency = RedisCluster::getInstance()->get($key);
            RedisCluster::getInstance()->remove($key);
            //获取信息
            $data = RedisCluster::getInstance()->get('guest_referer_data_' . $domain);
            RedisCluster::getInstance()->remove('guest_referer_data_' . $domain);
            if (empty($data)) {
                continue;
            } else {
                $data = json_decode($data, true);
            }
            $data['frequency'] = (int) $frequency;
            $this->saveFenxi($data);
        }
    }

    //记录分析结果
    protected function saveFenxi($data) {
        if (empty($data)) {
            return false;
        }
        $info = $this->find($this->where(array('years' => $data['years'], 'month' => $data['month'], 'day' => $data['day'], 'domain' => $data['domain'])));
        if (!empty($info)) {
            $info->frequency = $info->frequency + (int) $data['frequency'];
            return $info->save();
        } else {
            unset($this->id);
            $this->attributes = $data;
            $this->setIsNewRecord(true);
            return $this->save();
        }
    }

}
